package com.zb.api.business.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.server.HttpServerRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zb.api.business.entity.UserEntity;
import com.zb.api.business.service.UserService;
import com.zb.api.common.conts.Const;
import com.zb.api.common.models.Result;
import com.zb.api.common.models.ServerResponse;
import com.zb.api.common.models.UserVo;
import com.zb.api.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/testBoot")
public class UserController {

    @Resource
    private UserService userService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    JwtUtils jwtUtils;

    @RequestMapping("getUser/{id}")
    public UserEntity GetUser(@PathVariable int id){
        UserEntity userEntity = userService.Sel(id);
        return userEntity;
    }

    /**
     * 用户登录
     * @param userEntity
     * @return
     */
    @PostMapping("login")
    public ServerResponse login(@RequestBody UserEntity userEntity){

        // 验证码验证
        // 获取登录验证码的key
        String key = userEntity.getCaptchaKey();
        // 根据key从redis中获取value
        String redisCode = redisTemplate.opsForValue().get(Const.CAPTCHA_KEY_LOGIN+key);
        if(StringUtils.isEmpty(redisCode)){
            return ServerResponse.error(1000,"验证码过期");
        }

        // 对比 value 和传过来的 code
        if(!redisCode.equals(userEntity.getCode())){
            return ServerResponse.error(1001,"验证码错误");
        }
        // 验证码一次使用
        redisTemplate.delete(Const.CAPTCHA_KEY_LOGIN + key);
        // 根据用户名和密码查询是否存在此用户
        UserEntity userEntityInfo = userService.getUserByUserNameAndPassword(userEntity);
        if(userEntityInfo == null){
            // 用户名密码错误 需要重新请求生成验证码
            return ServerResponse.error(1002,"用户名或密码错误");
        }
        // 根据用户名生成jwt，并返回给前台
        String token = jwtUtils.generateToken(userEntity.getUsername());
        // 用户信息存入redis
        redisTemplate.opsForValue().set(Const.USER_INFO_KEY+token, JSONObject.toJSONString(userEntityInfo));
        // token 拼接一个常量作为key
        redisTemplate.expire(Const.USER_INFO_KEY+token, 7, TimeUnit.DAYS);
        Map<Object, Object> map = MapUtil.builder().put("Authorization", token).put("userInfo", userEntityInfo).map();
        return ServerResponse.success("登录成功",map);
    }


    /**
     * 判断用户名是否被使用
     * @param username
     * @return
     */
    @GetMapping("checkUserNameRepeat/{username}")
    public ServerResponse checkUserNameRepeat(@PathVariable("username") String username){
        // 根据用户名查询此用户是否已被使用
        UserEntity user = userService.getUserByUserName(username);
        if(user==null){
            return ServerResponse.success("此用户名可以使用");
        }

        return ServerResponse.error(100,"此用户名已被使用");
    }


    /**
     * 用户注册
     * @param userVo
     * @return
     */
    @PostMapping("register")
    public ServerResponse register(@RequestBody UserVo userVo){
        // 根据用户名和密码查询是否存在此用户
        String username = userVo.getUsername();
        UserEntity user = userService.getUserByUserName(username);
        if(user!=null){
            return ServerResponse.error(100,"此用户名已被使用");
        }
        // 判断两次密码是否一致
        String password = userVo.getPassword();
        String passwordTwice = userVo.getPasswordTwice();
        if(!password.equals(passwordTwice)){
            return ServerResponse.error(10002,"两次密码不一致");
        }
        userVo.setCreateTm(new Date().getTime());
        int result = userService.userRegister(userVo);
        if(result == 1){
            return ServerResponse.success("注册成功,请登录");
        }
        return ServerResponse.error(100,"注册失败");
    }

    /**
     * 用户信息修改
     * @param userVo
     * @return
     */
    @PostMapping("update")
    public ServerResponse update(@RequestBody UserVo userVo,HttpServerRequest request){

        int result = userService.updateUserInfo(userVo);
        if(result == 1){
            //String token = request.getHeader(jwtUtils.getHeader());
            //redisTemplate.delete(Const.USER_INFO_KEY + token);
            return ServerResponse.success("用户信息修改成功");
        }
        return ServerResponse.error(100,"用户信息修改失败");
    }

    /**
     * 用户修改密码
     * @param userVo
     * @return
     */
    @PostMapping("updatePassword")
    public ServerResponse updatePassword(@RequestBody UserVo userVo){
        // 旧密码
        String password = userVo.getPassword();
        // 要修改的密码
        String passwordTwice = userVo.getPasswordTwice();
        // 根据用户id查询用户信息
        UserEntity userEntity = userService.Sel(userVo.getId());
        String dataPass = userEntity.getPassword();
        if(!dataPass.equals(password)){
            throw new RuntimeException("输入的原始密码不正确");
        }

        int result = userService.updateUserPasswordById(passwordTwice,userVo.getId());
        if(result == 1){
            return ServerResponse.success("密码修改成功");
        }
        return ServerResponse.error(1002,"密码修改失败");
    }


    /**
     * 个人中心
     * @param userEntity
     * @return
     */
    @PostMapping("getUserInfo")
    public Result<UserEntity> getUserInfo(@RequestBody UserEntity userEntity){
        UserEntity userEntityInfo = userService.getUserInfo(userEntity);
        if(userEntityInfo ==null){
            return new Result("未找到用户信息");
        }
        return new Result("", userEntityInfo);
    }


}
